# _*_ coding:utf-8 _*_
# version 1.0
# author : wzp

import json
import os
import requests

# _token_file = "/root/wzp/test_return/token"
_token_file = "./token"

Secrets={
    "1000008":"vXCxDBz-Rcvhx4LBobkpcY6aYKcHhxO-ash68BBnKpo",
    "1000009":"O6ci473BlhyaPBE7AlJ5TrtwAn8Tad9StMSN1vcbuu4"
}

class Msg:
    token = _token_file

#定义消息类型 文本消息
class MsgText(Msg):
    def __init__(self,content,to_user="@all",application_id = 1000002,safe=0):
        self.data = {
            "touser": to_user,
            # "toparty": to_party,
            # "totag": 1,#to_tag
            "msgtype": "text",
            "agentid": application_id,
            "text": {
                "content": content,
            },
            "safe": safe
        }

#定义消息类型 Markdown消息   官网markdown消息似乎不支持表格
class MsgMarkdown(Msg):
    def __init__(self,content,to_user="@all",application_id=1000002):
        self.data = {
            "touser": to_user,
            # "toparty": to_party,
            # "totag": 1,#to_tag,
            "msgtype": "markdown",
            "agentid": application_id,
            "markdown": {
                "content": content,
            },
            "enable_duplicate_check": 0,
            "duplicate_check_interval": 1800
        }

class MsgImage(Msg):
    def __init__(self,content,to_user="@all",application_id=1000002):
        self.data = {
            "touser" : to_user,
            # "toparty" : "PartyID1|PartyID2",
            # "totag" : "TagID1 | TagID2",
            "msgtype" : "image",
            "agentid" : application_id,
            "image" : {
                "media_id" : content
            },
            "safe":0,
            "enable_duplicate_check": 0,
            "duplicate_check_interval": 1800
    }

class MsgCard(Msg):
    def __init__(self, content,title="Info",url = "www.baidu.com", to_user="@all", application_id=1000002):
        self.data = {
            "touser": to_user,
            # "toparty": "PartyID1 | PartyID2",
            # "totag": "TagID1 | TagID2",
            "msgtype": "textcard",
            "agentid": application_id,
            "textcard": {
                "title": title,
                "description": content,
                "url": url,
                "btntxt": "dont touch it"
            },
            "enable_id_trans": 0,
            "enable_duplicate_check": 0,
            "duplicate_check_interval": 1800
        }

class MsgMpnews(Msg):
    def __init__(self, content,media_id,title="Info",url = "www.baidu.com", to_user="@all", application_id=1000002):
        self.data = {
            "touser": to_user,
            # "toparty": "PartyID1 | PartyID2",
            # "totag": "TagID1 | TagID2",
            "msgtype": "mpnews",
            "agentid": application_id,
            "mpnews": {
                "articles": [
                    {
                        "title": title,
                        "thumb_media_id": media_id,
                        "author": "Author",
                        "content_source_url": url,
                        "content": content,
                        "digest": "Digest description"
                    }
                ]
            },
            "safe": 0,
            "enable_id_trans": 0,
            "enable_duplicate_check": 0,
            "duplicate_check_interval": 1800
        }

    ## 从官方获取token信息
def getTokenFromNet(CorpID="", Secret="",token_file = _token_file):
    print("读取网络token文件..")
    try:
        req = requests.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}".format(CorpID, Secret))
        r = json.loads(req.content)
        with open(token_file,"w") as f:
            f.write(r["access_token"])
        return r["access_token"]
    except Exception as e:
        print(e)

## 从本地token文件读取
def getTokenFromLocal(token_file=_token_file,agent_id="1000002"):
    token = ""
    if os.path.exists(token_file):
        print("读取本地token文件..")
        with open(token_file, "r") as f:
            token = str.strip(f.readline())
    else:
        if agent_id in Secrets:
            token = getTokenFromNet(token_file=token_file, Secret=Secrets[agent_id])
        else:
            token = getTokenFromNet(token_file=token_file)

    return token

##发送方法重写
def sendWechatMsg(classname):
    token = getTokenFromLocal(token_file=classname.token,agent_id=classname.data["agentid"])
    url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}'.format(token)
    data = classname.data
    data = json.dumps(data, ensure_ascii=False)
    print(data)
    req = requests.post(url, data.encode("utf-8"))
    r = json.loads(req.content)
    return r["errcode"]

##发送重试次数控制
def sendWechatMsgCtl(classname,send=sendWechatMsg):
    flag = 1
    trytimes = 1
    while trytimes <= 3 and flag >0 :
        r = send(classname)
        print("第{0}次执行结果为{1}".format(trytimes,r))
        if r != 0 :
            trytimes += 1
            if classname.data["agentid"] in Secrets:
                getTokenFromNet(token_file=classname.token,Secret=Secrets[classname.data["agentid"]])
            else:
                getTokenFromNet(token_file=classname.token)
        else:
            flag = 0

##兼容之前的方法
def send_msg(content,application_id='1000002'):
    sendWechatMsgCtl(MsgText(content,application_id=application_id))

def send_msgcard(content,title= "abc",application_id='1000002'):
    sendWechatMsgCtl(MsgCard(content,title=title,application_id=application_id))


if __name__ == '__main__':
    send_msg("中文测试2", application_id='1000008')
    # getTokenFromNet(CorpID="",
    #                 Secret="", token_file=_token_file)
    # o = MsgText("表头111")
    # sendWechatMsgCtl(MsgCard("MsgCard",title="111",url="http://xkctk.hangzhou.gov.cn/"))

    # pass